package com.hzlj.position.open.api.controller;


import com.fz.common.base.core.JsonUtils;
import com.fz.common.base.dto.ResultDTO;
import com.hzlj.position.open.api.common.dto.OpenApiAbnHandleKeyDTO;
import com.hzlj.position.open.api.common.dto.OpenApiAbnHandleUpdateDTO;
import com.hzlj.position.open.api.config.OpenApiPositionConfig;
import com.hzlj.sqjz.config.common.dto.common.handle.HandleCommonUpdateDTO;
import com.hzlj.sqjz.config.service.HandleCommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【行为记录】接口
 *
 * @author lifh
 * @date 2023-03-28 21:11:50
 */
@Slf4j
@RestController
@RequestMapping("/position/open/api/abn")
public class OpenApiAbnController {
    @Resource
    private OpenApiPositionConfig openApiPositionConfig;
    @Resource
    private HandleCommonService handleCommonService;

    /**
     * 行为异常处理(包含：聚集、夜不归宿、夜间活动、禁止区域、24小时无定位)
     */
    @PostMapping("/handle")
    public ResultDTO<Boolean> handle(@RequestHeader("appId") String appId,
                                     @RequestHeader("timestamp") String timestamp,
                                     @RequestHeader("sign") String sign,
                                     @RequestBody OpenApiAbnHandleUpdateDTO dto) {
        openApiPositionConfig.checkSign(appId, timestamp, sign);
        log.info("行为异常处理(openApi)：{}", JsonUtils.obj2json(dto));
        Map<String, List<String>> idsByType = dto.getKeys().stream()
                .collect(Collectors.groupingBy(OpenApiAbnHandleKeyDTO::getType, Collectors.mapping(OpenApiAbnHandleKeyDTO::getId, Collectors.toList())));

        for (Map.Entry<String, List<String>> entry : idsByType.entrySet()) {
            String type = entry.getKey();
            HandleCommonUpdateDTO<String> update = new HandleCommonUpdateDTO<>();
            update.setIds(entry.getValue());
            update.setHandleExt(dto.getHandleExt());
            update.setHandleStatus(dto.getHandleStatus());
            update.setHandleTime(dto.getHandleTime());

            switch (type) {
                case "20":
                    update.setHandler("AbnGathering");
                    break;
                case "21":
                    update.setHandler("AbnNightOut");
                    break;
                case "22":
                    update.setHandler("AbnNightActivity");
                    break;
                case "23":
                    update.setHandler("AbnProhibitAreasPosition");
                    break;
                case "24":
                    update.setHandler("AbnNoRecord");
                    break;
            }
            handleCommonService.handle(update);
        }
        return ResultDTO.ok();
    }

}

